import os
import sys
from flask import Flask, jsonify
from flask_cors import CORS
from flask_swagger import swagger
from flask_swagger_ui import get_swaggerui_blueprint

# 将搜索目录改为本级目录
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__))))

# 导入蓝图
from routes.common import common_bp
from routes.develop import develop_bp
from routes.orchestrate import orchestrate_bp
from routes.deploy import deploy_bp
from routes.monitor import monitor_bp

# 服务常量定义
atom_service_develop = "develop"
atom_service_orchestrate = "orchestrate"
atom_service_deploy = "deploy"
atom_service_monitor = "monitor"
atom_service_common = "common"

app = Flask(__name__)

# 添加Swagger配置
app.config['SWAGGER'] = {
    'specs_route': '/swagger.json',
    'title': '服务器API文档',
    'version': '1.0',
    'description': '微服务编译系统API接口文档'
}
# 导入并初始化Swagger
swagger(app)

# 允许所有路由的所有来源访问
CORS(app)  

# Swagger UI 配置
SWAGGER_URL = "/docs"
API_URL = "/swagger.json"
# 创建Swagger UI蓝图
swaggerui_blueprint = get_swaggerui_blueprint(
    SWAGGER_URL,
    API_URL,
    config={  # 配置Swagger UI
        'app_name': "微服务编译系统API文档"
    }
)
# 注册Swagger UI蓝图
app.register_blueprint(swaggerui_blueprint, url_prefix=SWAGGER_URL)

# 注册蓝图
app.register_blueprint(develop_bp, url_prefix=f"/{atom_service_develop}")
app.register_blueprint(orchestrate_bp, url_prefix=f"/{atom_service_orchestrate}")
app.register_blueprint(deploy_bp, url_prefix=f"/{atom_service_deploy}")
app.register_blueprint(monitor_bp, url_prefix=f"/{atom_service_monitor}")
app.register_blueprint(common_bp, url_prefix=f"/{atom_service_common}")



@app.route("/")
def hello_world():
    return "Hello, World!"


# 添加全局错误处理器，捕获500错误
@app.errorhandler(500)
def internal_server_error(e):
    print(f"发生500错误: {str(e)}")
    return f"服务器内部错误: {str(e)}", 500


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5173, debug=True)